package com.it.feign.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.*;
import org.springframework.web.util.UriComponentsBuilder;

import javax.annotation.Resource;
import java.util.Map;
import java.util.UUID;

import static org.springframework.util.CollectionUtils.newHashMap;

/**
 * RestTemplate请求示例, 相比较feign更复杂
 */
@Slf4j
@RestController
@RequestMapping("/api/RestTemplateRequestController")
public class RestTemplateRequestController {

    @Resource
    private RestTemplate restTemplate;

    @GetMapping("/testRestTemplateRequest")
    public String testRestTemplateRequest() throws RuntimeException {
        Map<String, Object> searchParams = newHashMap(8);
        searchParams.put("id", "1");
        int page = 1;
        int size = 10;
        String authToken = "authToken";

        // 1. 构建URL和查询参数
        String url = "http://localhost:20819/api/FeignController/hello";

        // 添加分页参数
        MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<>();
        queryParams.add("page", String.valueOf(page));
        queryParams.add("size", String.valueOf(size));

        // 添加搜索条件参数
        searchParams.forEach((key, value) -> {
            if (value != null) {
                queryParams.add(key, value.toString());
            }
        });

        // 2. 构建Headers
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + authToken);
        headers.set("X-Request-ID", UUID.randomUUID().toString());

        // 3. 构建请求实体
        HttpEntity<?> requestEntity = new HttpEntity<>(headers);

        // 4. 构建URI（包含查询参数）
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url)
                .queryParams(queryParams);

        try {
            // 5. 发送请求
            ResponseEntity<String> response = restTemplate.exchange(
                    builder.build().toUri(),
                    HttpMethod.GET,
                    requestEntity,
                    String.class
            );

            // 6. 处理响应
            if (response.getStatusCode() == HttpStatus.OK && response.hasBody()) {
                return response.getBody();
            }
            throw new RuntimeException("Empty response body");

        } catch (HttpClientErrorException e) {
            // 4xx错误处理
            if (e.getStatusCode() == HttpStatus.UNAUTHORIZED) {
                throw new RuntimeException("Authentication failed", e);
            } else if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
                return "";
            }
            throw new RuntimeException("Client error: " + e.getResponseBodyAsString(), e);

        } catch (HttpServerErrorException e) {
            // 5xx错误处理
            throw new RuntimeException("Server error: " + e.getResponseBodyAsString(), e);

        } catch (ResourceAccessException e) {
            // 超时或连接问题
            throw new RuntimeException("Service unavailable: " + e.getMessage(), e);

        } catch (RestClientException e) {
            // 其他RestTemplate异常
            throw new RuntimeException("Communication error: " + e.getMessage(), e);
        }
    }

}
